import pymysql
from dbutils.pooled_db import PooledDB
import threading

# 线程
from threading import Thread


"""
storage = {
    111:{'stack':[(conn, cursor),]},
    222:{'stack':[(conn, cursor),]},
}
"""


class SqlHelper(object):
    # 初始化
    def __init__(self) -> None:
        # 创建数据库连接池
        self.pool = PooledDB(
            creator=pymysql,  # 使用链接数据库的模块
            maxconnections=6,  # 连接池允许的最大连接数，0和None表示不限制连接数
            mincached=2,  # 初始化时，链接池中至少创建的空闲的链接，0表示不创建
            blocking=True,  # 连接池中如果没有可用连接后，是否阻塞等待。True，等待；False，不等待然后报错
            # ping MySQL服务端，检查是否服务可用。# 如：0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always
            ping=0,
            host="localhost",
            port=3306,
            user="root",
            password="123456",
            database="flasktest",
            charset="utf8",
        )
        self.local = threading.local()

    # 获取连接、游标
    def open(self):
        # 去连接池中获取一个连接
        conn = self.pool.connection()

        cursor = conn.cursor()

        return conn, cursor

    # 关闭
    def close(self, conn, cursor):
        # 将连接放回到连接池
        cursor.close()
        conn.close()

    # 获取所有数据
    def fetchall(self, sql, *args):
        # 连接数据库，获取游标
        conn, cursor = self.open()

        cursor.execute(sql, args)
        result = cursor.fetchall()

        # 关闭数据库
        self.close(conn, cursor)

        return result

    # 获取单条数据
    def fetchone(self, sql, *args):
        # 连接数据库，获取游标
        conn, cursor = self.open()

        cursor.execute(sql, args)
        result = cursor.fetchone()

        # 关闭数据库
        self.close(conn, cursor)

        return result

    # with enter
    def __enter__(self):
        conn, cursor = self.open()

        # 通过getattr在self.local中获取stack变量，如果没有获取则为None
        rv = getattr(self.local, "stack", None)
        if not rv:  # 不存在stack，则新增stack
            # self.local有线程id
            self.local.stack = [
                (conn, cursor),
            ]
        else:  # 存在stack，则追加(conn, cursor),元组
            rv.append(
                (conn, cursor),
            )
            self.local.stack = rv

        return cursor

    # with exit
    def __exit__(self, exc_type, exc_val, excc_tb):
        rv = getattr(self.local, "stack", None)
        if not rv:  # rv中没有值，什么都不做
            return

        # 拿到conn, cursor并关闭
        conn, cursor = self.local.stack.pop()
        cursor.close()
        conn.close()


# db包含一个pool和一个local
db = SqlHelper()


    
